var supplier_box_count = 1;
var drag_src = null;

$(document).ready(function(){
	$('.material_1').bind('dragstart', drag_start);
	$('.material_1').bind('click', function(e) { $('.material_1').selText() });
	$('.material_2').bind('dragstart', drag_start);
	$('.material_3').bind('dragstart', drag_start);
});

function add_supplier()
{
	var new_box = $('.supplier_box').first().clone(); //clone first supplier box found	
	new_box.find('.remove_button').attr('href', 'javascript: remove_supplier(' + supplier_box_count +')');
	new_box[0].addEventListener('dragenter', drag_enter, false);
	new_box[0].addEventListener('dragleave', drag_leave, false);
	new_box[0].addEventListener('dragover', drag_over, false);
	new_box[0].addEventListener('drop', drag_drop, false);
	new_box.children('.content_box').addClass('supplier_box_' + supplier_box_count);
	$('#suppliers_box').append(new_box);
	new_box.show();
	supplier_box_count++;
}

function remove_supplier(id)
{
	$('.supplier_box_' + id).parent().remove();
}

function drag_start(e)
{
	var dt = e.originalEvent.dataTransfer;
	dt.effectAllowed = 'move';
	dt.setData("Text", "for firefox purposes");	
	drag_source = this;
	
	return true;
}

function drag_over(e)
{
	if (e.preventDefault) 
	{
		e.preventDefault(); // Necessary. Allows us to drop.
	}
	
	e.dataTransfer.dropEffect = 'move';
	$(this).find('.content_box').addClass('active');
	return false;
}

function drag_enter(e)
{
	$(this).find('.content_box').addClass('active');
}

function drag_leave(e)
{
	$(this).find('.content_box').removeClass('active');
}

function drag_drop(e) 
{
	$(this).find('.content_box').removeClass('active');
	
	var material = $.parseJSON($(drag_source).find('input').val());
	
	$(this).find('table').append(
		'<tr>' +
			'<td><select><option>Normal</option><option>MOQ</option><option>Split</option></select></td>' +
			'<td>' + material.code +
			'</td><td>' + material.name +
			'</td><td><input type="number" value="' + material.quantity + '" style="width:75px" />' +
			'</td><td>' + material.unit +
			'</td><td><input type="number" style="width:75px"  /><td><input type="number" style="width:75px" /></td></tr>'			
	);	

	e.stopPropagation();
	return false;
}